package com.anlu.zk.curator;

import com.anlu.zk.core.ZooKeeperDistributedLock;
import com.anlu.zk.simple.OrderService;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author 郑斌.
 * Description:
 * Last Modify User:
 * Date: 2019-09-25
 * Time: 14:46
 */
public class DLockTest1 {


    private static List<String> msgCache = new ArrayList<String>();
    //发令枪，模拟50个并发
    private static CountDownLatch countDownLatch = new CountDownLatch(50);

    private static int number=0;

    public static void main(String[] args) {

        String zkAddress = "127.0.0.1:2181";

        String lockPath = "/distribute-locktest";
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(zkAddress)
                .sessionTimeoutMs(2000)
                .retryPolicy(retryPolicy)
                .build();
        curatorFramework.start() ;

        final InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);
        for (int i=0;i<50;i++){
            new Thread(new anluOrder(lock)).start();
        }
        try {
            countDownLatch.await();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("最后的number="+number);
    }



    private static class anluOrder implements Runnable{

        private InterProcessLock lock;

        public anluOrder(InterProcessLock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            countDownLatch.countDown();
//            System.out.println(Thread.currentThread().getName() + " acquire");
            try {
                lock.acquire();
                number=number+1;
                System.out.println(Thread.currentThread().getName() + " acquire success"+"="+number);
//                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                System.out.println(Thread.currentThread().getName() + " release");
                try {
                lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            System.out.println(Thread.currentThread().getName() + " release success");
        }
    }

}
